import React, { useEffect, useState, useRef } from 'react';
import { Divider, Popconfirm, Popover, Steps, Table } from 'antd';
import { showMsg, MsgType, isNull } from '@/utils/utils';
import ProTable, { ProColumns } from '@ant-design/pro-table';
import { getApplyInfo, auditStoreApplyInfo } from '@/services/shop/api'
import PopoverContent from '@/components/PopoverContent/Index';
import PermissionControl from '@/components/PermissionControl';
import Auditing from '@/components/Auditing';

const ApplyInfo: React.FC<{apply_id: string; title: string; applyInfo: Object; onRefresh: Function}> = (props) => {
  const { apply_id, title, applyInfo={}, onRefresh } = props;
  const [steps, setSteps] = useState<any[]>([])
  const [currentStep, setCurrentStep] = useState<number>(0)
  const [list, setList] = useState<any[]>([])
  const [visible, setVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [showSpSuccess, setShowSpSuccess] = useState(false);
  const auditingRef = useRef();

  const columns: ProColumns<any>[] = [
    {
      title: '申请单号',
      dataIndex: 'apply_id',
      className: 'wordbreak',
      width: 165
    },
    {
      title: '原订单号',
      dataIndex: 'order_id',
      width: 120
    },
    {
      title: '申请时间',
      dataIndex: 'apply_time',
      valueType: 'dateTime',
      width: 140,
    },
    {
      title: '用户账号',
      dataIndex: 'user_name',
      width: 100
    },
    {
      title: '订单退款',
      align: 'right',
      valueType: 'money',
      dataIndex: 'refund_fee',
      width: 90
    },
    {
      title: '退快递费',
      align: 'right',
      valueType: 'money',
      dataIndex: 'mail_price',
      width: 60
    },
    {
      title: '售后方式',
      dataIndex: 'way',
      valueType: 'select',
      valueEnum: {
        1: '退货', 
        2: '退款'
      }
    },
    {
      title: '申请状态',
      dataIndex: 'apply_status',
      valueType: 'select',
      valueEnum: {
        U: '待处理',
        H: '受理中',
        S: '已完成', 
        F: '已拒绝',
        C: '已撤销'
      }
    },
    {
      title: '售后状态',
      dataIndex: 'after_sales_status',
      valueType: 'select',
      valueEnum: {
        W: '待收货', 
        I: '退款中', 
        R: '已退款',
        M: '待收货'
      },
      render: (val, record) => {
        if (record.after_sales_status === 'M') {
          return record.return_way === '1' ? '待寄回' : '待送回'
        }
        return val;
      }
    },
  ];

  if (applyInfo.apply_status === 'U') {
    columns.push({
      title: '操作',
      align: 'center',
      valueType: 'option',
      width: 130,
      render: (dom, entity) => {
        const {apply_status, after_sales_status, way } = entity

        if (apply_status === 'U') {
          return [
            <PermissionControl key="agree" action_id="600613003">
              <Popconfirm 
                okText="确认通过"
                cancelText="再想想"
                okButtonProps={{
                  loading: confirmLoading
                }}
                visible={showSpSuccess}
                onConfirm={async () => {
                  if (confirmLoading) {
                    return;
                  }
                  setConfirmLoading(true);
                  const data = {
                    apply_id,
                    audit: 'PASS',
                    Action_Id: '600613003'
                  }
                  auditingRef?.current?.onSign({sign_no: apply_id, sign_string: JSON.stringify(data), title: `小程序${entity.way === '1' ? '退货' : '退款'}审批`}, async() => {
                    await auditStoreApplyInfo(data).then(res => {
                      showMsg('已审批', MsgType.SUCCESS);
                      setConfirmLoading(false);
                      // await fetchApplyInfo()
                      onRefresh();
                    }).catch(error => {
                      setLoading(false);
                      setConfirmLoading(false);
                      showMsg(error?.data?.errmsg)
                    });
                  })
                }}
                onCancel={() => setShowSpSuccess(false)}
                title={<div>审核通过后，系统将自动发起退款流程，<br />请核对确认当前商品尚未发货</div>}>
                <Auditing
                  ref={auditingRef}
                  loading={loading}
                  module='MR'
                  onLoading={e => setLoading(e)}
                  onError={() => {
                    setLoading(false);
                  }}
                  onClick={() => {
                    setShowSpSuccess(true);
                    // agree()
                  }}
                  _html={<a>审核通过</a>}
                />
              </Popconfirm>
            </PermissionControl>,
            <PermissionControl  key="reject" action_id="600613004">
              <Popover 
                visible={visible}
                // onVisibleChange={setVisible}
                content={ <PopoverContent 
                  confirmText="确认" 
                  onCancel={() => {
                    setVisible(false);
                  }}
                  loading={loading}
                  onConfirm={ async (value: string) => {
                  try {
                    if (loading) {
                      return
                    }
                    setLoading(true);
                    const data = {
                      apply_id,
                      audit: 'FAIL',
                      refuse_reason: value,
                      Action_Id: '600613004'
                    };
                    auditingRef?.current?.onSign({sign_no: apply_id, sign_string: JSON.stringify(data), title: `小程序${entity.way === '1' ? '退货' : '退款'}审批`}, async() => {
                      await auditStoreApplyInfo(data).then(async(res) => {
                        showMsg('已审批', MsgType.SUCCESS);
                        setLoading(false);
                        setVisible(false);
                        onRefresh()
                      }).catch(error => {
                        setLoading(false);
                        showMsg(error?.data?.errmsg)
                      });
                    });
                  } catch (error) {
                    setLoading(false);
                    showMsg(error?.data?.errmsg);
                  }
                }} /> }
                trigger="click">
                  <Auditing
                    ref={auditingRef}
                    loading={loading}
                    module='MR'
                    onLoading={e => setLoading(e)}
                    onError={() => {
                      setLoading(false);
                    }}
                    onClick={() => {
                      setVisible(true)
                    }}
                    _html={<a>审核拒绝</a>}
                  />
              </Popover>
            </PermissionControl>
          ]
        }
        return []
      }
    });
  }

  const fetchApplyInfo = async (data) => {
    try {
      // const data = await getApplyInfo(apply_id)
      // setApplyInfo(data)
      const item = {
        apply_id: data.apply_id,
        order_id: data.order_id,
        apply_time: data.apply_time,
        user_name: data.user_name,
        refund_fee: data.refund_fee,
        mail_price: data.mail_price,
        way: data.way,
        apply_status: data.apply_status,
        after_sales_status: data.after_sales_status,
        apply_reason: data.apply_reason,
        refuse_reason: data.refuse_reason,
        return_way: data.return_way,
      }
      setList([item]);
      const step = [
        {
          title: '提交申请',
          description: `${data.apply_time}`,
          status: data.apply_time ? 'finish' : 'wait'
        },
      ];
      if (data.apply_status === 'F') {
        step.push({
          title: '已拒绝',
          description: data.audit_time,
          status: 'finish',
          width: 150,
        });
      } else {
        const finish = data.apply_status === 'S' || data.after_sales_status === 'W' || data.after_sales_status === 'R';
        step.push({
          title: '审核通过',
          description: finish ? data.audit_time : '',
          status: finish ? 'finish' : 'wait'
        });
        if (data.way === '1') {
          step.push({
            title: '确认收货',
            description: data.receive_goods_time,
            status: data.after_sales_status === 'W' || data.after_sales_status === 'R' ? 'finish' : 'wait'
          },);
        }
        step.push({
          title: '确认退款',
          status: data.after_sales_status === 'R' ? 'finish' : 'wait',
          description: data.refund_time
        },
        {
          title: '处理完成',
          status: data.after_sales_status === 'R' ? 'finish' : 'wait',
        });
      }
      setSteps(step) 
    } catch (error) {
      showMsg(error?.data?.errmsg)
    }
  }

  useEffect(() => {
    // setApplyInfo(applyInfo);
    if (!isNull(applyInfo)) {
      fetchApplyInfo(applyInfo);
    }
  }, [applyInfo]);

  console.log('applyInfo', applyInfo)

  return <div className="service-record after-record">
      <Steps current={currentStep} labelPlacement="vertical">
        {
          steps.map((item, index) => {
            return <Steps.Step key={index} status={item.status} title={item.title} description={item.description} />
          })
        }
      </Steps>
      
      <div className="header" style={{marginTop: 20}}>
        <div className="title">{title}</div>
      </div>

      <Divider style={{margin: '10px 0 0 !important'}} />
      
      <ProTable<any> 
        bordered  
        options={false} 
        loading={loading}
        style={{ marginTop: -5 }}
        search={false} 
        rowKey="apply_id"
        dataSource={list}
        columns={columns} 
        pagination={false}
        summary={pageData => {
          let apply_reason = ''
          let refuse_reason = ''
          pageData.forEach(item => {
            apply_reason = item.apply_reason
            refuse_reason = item.refuse_reason
          })
          return (
            <>
              <Table.Summary.Row className='reason-row'>
                <Table.Summary.Cell index={1}>申请售后原因</Table.Summary.Cell>
                <Table.Summary.Cell colSpan={9} index={1}>{apply_reason}</Table.Summary.Cell>
              </Table.Summary.Row>
              {
                !isNull(refuse_reason) &&
                <Table.Summary.Row className='reason-row'>
                  <Table.Summary.Cell index={1}>审批拒绝原因</Table.Summary.Cell>
                  <Table.Summary.Cell colSpan={9} index={2}>{refuse_reason}</Table.Summary.Cell>
                </Table.Summary.Row>
              }
            </>
          )
        }} 
        />
  </div>
}
export default ApplyInfo;